﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Network.ThreadBase;

public abstract class ThreadBase
{
    public ThreadBase(string name)
    {
        ThreadName = name;
        ShouldRun = false;
    }
    public bool Start()
    {
        lock (ShouldRunMutex)
        {
            if (ShouldRun)
                return false;
            ShouldRun = true;
        }
        Thread = new Thread(ThreadFunc);
        Thread.Start();
        return true;
    }

    public void Stop()
    {
        ShouldRun = false;
    }
    public void Join()
    {
        Thread?.Join();
    }
    public void ThreadFunc()
    {
        ThreadInit();
        while (ShouldRun)
        {
            Run();
        }
        ThreadExit();
    }
    public virtual void ThreadInit()
    {
        Console.WriteLine($"Thread:{ThreadName} Start!");
    }
    public virtual void ThreadExit()
    {
        Console.WriteLine($"Thread:{ThreadName} Exit!");
    }
    protected abstract void Run();

    protected Thread? Thread;
    protected string ThreadName;
    protected bool ShouldRun;
    protected object ShouldRunMutex = new object();
}
